package com.huilan.util;

import com.huilan.model.User;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ghy
 */
public class JwtUtil {
    private static Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    /**
     * jwt 过期时间 30分钟
     */
    public static final long EXPIRATION_TIME = 30 * 60;
    public static final String AUTHORIZATION_HEADER_PREFIX = "Bearer ";
    public static final String SIGNING_KEY = "PrivateSecret";
    public static final String AUTHORIZATION = "Authorization";



    public static final String USER_ID = "id";
    public static final String USER_NAME = "username";
    public static final String ORG_ID = "orgId";

    /**
     * remove 'Bearer ' string
     *
     * @param authorizationHeader
     * @return
     */
    public static String getRawToken(String authorizationHeader) {
        return authorizationHeader.substring(AUTHORIZATION_HEADER_PREFIX.length());
    }

    public static String getTokenHeader(String rawToken) {
        return AUTHORIZATION_HEADER_PREFIX + rawToken;
    }

    public static boolean validate(String authorizationHeader) {
        return StringUtils.hasText(authorizationHeader) && authorizationHeader.startsWith(AUTHORIZATION_HEADER_PREFIX);
    }

    public static String getAuthorizationHeaderPrefix() {
        return AUTHORIZATION_HEADER_PREFIX;
    }

    /**
     * 创建JWT
     * @param user
     * @return
     */
    public static String createJWT(User user){
        Map<String,Object> map = new HashMap<String,Object>(16);
        map.put(USER_ID, user.getUserId());
        map.put(USER_NAME, user.getUsername());
        String token = Jwts.builder().setClaims(map)
//                .setSubject(user.getUserName()).setId(user.getUserId())
//                .setExpiration(new Date(System.currentTimeMillis() + (JwtUtil.EXPIRATION_TIME + 600 )))
                .signWith(SignatureAlgorithm.HS512, JwtUtil.SIGNING_KEY)
                .compact();
        return  JwtUtil.getTokenHeader(token);
    }


    /**
     * 解析JWT
     */
    public static Claims parseJWT(String token){
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(JwtUtil.SIGNING_KEY)
                    .parseClaimsJws(token.replace(JwtUtil.getAuthorizationHeaderPrefix(), ""))
                    .getBody();
            return claims;
        } catch (ExpiredJwtException e) {
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>Token已过期！");
            e.printStackTrace();
        } catch (UnsupportedJwtException e) {
            e.printStackTrace();
        } catch (MalformedJwtException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

        return null;
    }











    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private static String generateToken(Map<String, Object> claims) {
        Date expirationDate = new Date(System.currentTimeMillis() + 2592000L * 1000);
        return Jwts.builder().setClaims(claims).setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512, SIGNING_KEY).compact();
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(SIGNING_KEY).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }


    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 判断令牌是否过期
     *
     * @param token 令牌
     * @return 是否过期
     */
    public Boolean isTokenExpired(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            Date expiration = claims.getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 刷新令牌
     *
     * @param token 原令牌
     * @return 新令牌
     */
    public String refreshToken(String token) {
        String refreshedToken;
        try {
            Claims claims = getClaimsFromToken(token);
            claims.put("created", new Date());
            refreshedToken = generateToken(claims);
        } catch (Exception e) {
            refreshedToken = null;
        }
        return refreshedToken;
    }

    /**
     * 验证令牌
     *
     * @param token       令牌
     * @param userDetails 用户
     * @return 是否有效
     */
//    public Boolean validateToken(String token, UserDetails userDetails) {
//        JwtUser user = (JwtUser) userDetails;
//        String username = getUsernameFromToken(token);
//        return (username.equals(user.getUsername()) && !isTokenExpired(token));
//    }

}
